SELECT i.QuestionCode,i.QusDescription,s.cPlanNo,s.cState
INTO #temp
FROM FB_Question_Input i WITH(NOLOCK)
LEFT JOIN FB_QuestionPlanState s WITH(NOLOCK) ON i.ID=s.ParentID 
WHERE ERPCode=@cERPNo AND i.bFlag=1
DECLARE @SqlSubject VARCHAR(500)
SELECT @SqlSubject= STUFF((SELECT ','+'['+cPlanNo+']' FROM(
	SELECT DISTINCT e.cPlanNo 
	FROM [LS_LeadPMP_leadpmp].[LeadPMP].[dbo].[ScPlanStaticsMain] m WITH(NOLOCK)
	INNER JOIN [LS_LeadPMP_leadpmp].[LeadPMP].[dbo].[ScPlanStaticsEntry] e WITH(NOLOCK) ON m.dID=e.dID
	WHERE ISNULL(m.cCustomer,'')=@cCustomer AND e.cERPNo=@cERPNo
) T FOR XML PATH('')),1,1,'')
DECLARE @SqlPIVOT VARCHAR(600)='SELECT * FROM #temp PIVOT(MAX(cState) FOR cPlanNo IN('+@SqlSubject+')) T'
EXEC(@SqlPIVOT)
DROP TABLE #temp